<!--
  智慧社区管理系统 - 停车记录管理
  @author Wu.Liang
  @date 2024-01-01
-->
<template>
    <div class="record-container">
            <!-- 搜索区域 -->
            <el-card class="search-card">
                <el-form :model="searchForm" inline>
                    <el-form-item label="停车场">
                        <el-select v-model="searchForm.lotId" placeholder="请选择停车场" clearable>
                            <el-option
                                v-for="lot in parkingLots"
                                :key="lot.id"
                                :label="lot.lotName"
                                :value="lot.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="车牌号">
                        <el-input v-model="searchForm.licensePlate" placeholder="请输入车牌号" clearable />
                    </el-form-item>
                    <el-form-item label="支付状态">
                        <el-select v-model="searchForm.paymentStatus" placeholder="请选择支付状态" clearable>
                            <el-option label="未支付" :value="0" />
                            <el-option label="已支付" :value="1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="记录类型">
                        <el-select v-model="searchForm.recordType" placeholder="请选择记录类型" clearable>
                            <el-option label="临时停车" :value="1" />
                            <el-option label="月租停车" :value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="时间范围">
                        <el-date-picker
                            v-model="dateRange"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>

            <!-- 统计区域 -->
            <el-card class="statistics-card">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <div class="statistics-item">
                            <div class="statistics-title">总停车次数</div>
                            <div class="statistics-value">{{ statistics.totalCount || 0 }}</div>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="statistics-item">
                            <div class="statistics-title">今日停车次数</div>
                            <div class="statistics-value">{{ statistics.todayCount || 0 }}</div>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="statistics-item">
                            <div class="statistics-title">总收入</div>
                            <div class="statistics-value">¥{{ statistics.totalIncome || 0 }}</div>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="statistics-item">
                            <div class="statistics-title">今日收入</div>
                            <div class="statistics-value">¥{{ statistics.todayIncome || 0 }}</div>
                        </div>
                    </el-col>
                </el-row>
            </el-card>

            <!-- 操作区域 -->
            <el-card class="operation-card">
                <el-button type="primary" @click="handleVehicleEntry">车辆入场</el-button>
                <el-button type="success" @click="handleVehicleExit">车辆出场</el-button>
                <el-button type="warning" @click="handleRefresh">刷新</el-button>
                <el-button type="info" @click="handleExport">导出</el-button>
            </el-card>

            <!-- 数据表格 -->
            <el-card class="table-card">
                <el-table :data="filteredTableData" border v-loading="loading">
                    <el-table-column prop="id" label="ID" width="80" />
                    <el-table-column prop="recordNo" label="记录编号" width="120" />
                    <el-table-column prop="lotName" label="停车场" />
                    <el-table-column prop="spaceNo" label="车位号" width="100" />
                    <el-table-column prop="licensePlate" label="车牌号" width="120" />
                    <el-table-column prop="entryTime" label="进入时间" width="180" />
                    <el-table-column prop="exitTime" label="离开时间" width="180" />
                    <el-table-column prop="parkingDuration" label="停车时长(分钟)" width="120" />
                    <el-table-column prop="parkingFee" label="停车费用" width="100">
                        <template #default="{ row }">
                            ¥{{ row.parkingFee || 0 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="paymentStatusName" label="支付状态" width="100">
                        <template #default="{ row }">
                            <el-tag :type="row.paymentStatus === 1 ? 'success' : 'danger'">
                                {{ row.paymentStatusName }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="recordTypeName" label="记录类型" width="100" />
                    <el-table-column label="操作" width="200" fixed="right">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="handleDetail(row)">详情</el-button>
                            <el-button type="success" size="small" @click="handleCalculateFee(row)" v-if="!row.exitTime">计算费用</el-button>
                            <el-button type="warning" size="small" @click="handlePayment(row)" v-if="row.paymentStatus === 0">支付</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-container">
                    <el-pagination
                        v-model:current-page="pagination.current"
                        v-model:page-size="pagination.size"
                        :page-sizes="[10, 20, 50, 100]"
                        :total="pagination.total"
                        layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </div>
            </el-card>

            <!-- 车辆入场对话框 -->
            <el-dialog
                v-model="entryDialogVisible"
                title="车辆入场"
                width="400px"
            >
                <el-form :model="entryForm" :rules="entryRules" ref="entryFormRef" label-width="100px">
                    <el-form-item label="停车场" prop="lotId">
                        <el-select v-model="entryForm.lotId" placeholder="请选择停车场" style="width: 100%">
                            <el-option
                                v-for="lot in parkingLots"
                                :key="lot.id"
                                :label="lot.lotName"
                                :value="lot.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="车牌号" prop="licensePlate">
                        <el-input v-model="entryForm.licensePlate" placeholder="请输入车牌号" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="entryDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleEntrySubmit" :loading="submitLoading">确定</el-button>
                </template>
            </el-dialog>

            <!-- 车辆出场对话框 -->
            <el-dialog
                v-model="exitDialogVisible"
                title="车辆出场"
                width="400px"
            >
                <el-form :model="exitForm" :rules="exitRules" ref="exitFormRef" label-width="100px">
                    <el-form-item label="车牌号" prop="licensePlate">
                        <el-input v-model="exitForm.licensePlate" placeholder="请输入车牌号" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="exitDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleExitSubmit" :loading="submitLoading">确定</el-button>
                </template>
            </el-dialog>

            <!-- 详情对话框 -->
            <el-dialog
                v-model="detailDialogVisible"
                title="停车记录详情"
                width="600px"
            >
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="记录编号">{{ currentRecord.recordNo }}</el-descriptions-item>
                    <el-descriptions-item label="停车场">{{ currentRecord.lotName }}</el-descriptions-item>
                    <el-descriptions-item label="车位号">{{ currentRecord.spaceNo }}</el-descriptions-item>
                    <el-descriptions-item label="车牌号">{{ currentRecord.licensePlate }}</el-descriptions-item>
                    <el-descriptions-item label="进入时间">{{ currentRecord.entryTime }}</el-descriptions-item>
                    <el-descriptions-item label="离开时间">{{ currentRecord.exitTime || '未出场' }}</el-descriptions-item>
                    <el-descriptions-item label="停车时长">{{ currentRecord.parkingDuration || 0 }}分钟</el-descriptions-item>
                    <el-descriptions-item label="停车费用">¥{{ currentRecord.parkingFee || 0 }}</el-descriptions-item>
                    <el-descriptions-item label="支付状态">{{ currentRecord.paymentStatusName }}</el-descriptions-item>
                    <el-descriptions-item label="记录类型">{{ currentRecord.recordTypeName }}</el-descriptions-item>
                </el-descriptions>
            </el-dialog>
        </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { showMessage } from '@/utils/message'


// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const entryDialogVisible = ref(false)
const exitDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const entryFormRef = ref<FormInstance>()
const exitFormRef = ref<FormInstance>()

// 静态数据
const allTableData = ref([
    {
        id: 1,
        recordNo: 'PR20241201001',
        lotName: 'A区停车场',
        spaceNo: 'A-001',
        licensePlate: '京A12345',
        entryTime: '2024-12-01 08:30:00',
        exitTime: '2024-12-01 12:30:00',
        parkingDuration: 240,
        parkingFee: 20,
        paymentStatus: 1,
        paymentStatusName: '已支付',
        recordType: 1,
        recordTypeName: '临时停车'
    },
    {
        id: 2,
        recordNo: 'PR20241201002',
        lotName: 'B区停车场',
        spaceNo: 'B-005',
        licensePlate: '京B67890',
        entryTime: '2024-12-01 09:15:00',
        exitTime: null,
        parkingDuration: null,
        parkingFee: 0,
        paymentStatus: 0,
        paymentStatusName: '未支付',
        recordType: 2,
        recordTypeName: '月租停车'
    },
    {
        id: 3,
        recordNo: 'PR20241201003',
        lotName: 'A区停车场',
        spaceNo: 'A-003',
        licensePlate: '京C11111',
        entryTime: '2024-12-01 10:00:00',
        exitTime: '2024-12-01 11:30:00',
        parkingDuration: 90,
        parkingFee: 15,
        paymentStatus: 1,
        paymentStatusName: '已支付',
        recordType: 1,
        recordTypeName: '临时停车'
    },
    {
        id: 4,
        recordNo: 'PR20241201004',
        lotName: 'C区停车场',
        spaceNo: 'C-002',
        licensePlate: '京D22222',
        entryTime: '2024-12-01 14:20:00',
        exitTime: '2024-12-01 18:20:00',
        parkingDuration: 240,
        parkingFee: 20,
        paymentStatus: 0,
        paymentStatusName: '未支付',
        recordType: 1,
        recordTypeName: '临时停车'
    },
    {
        id: 5,
        recordNo: 'PR20241201005',
        lotName: 'B区停车场',
        spaceNo: 'B-008',
        licensePlate: '京E33333',
        entryTime: '2024-12-01 16:45:00',
        exitTime: null,
        parkingDuration: null,
        parkingFee: 0,
        paymentStatus: 0,
        paymentStatusName: '未支付',
        recordType: 2,
        recordTypeName: '月租停车'
    }
])

const parkingLots = ref([
    { id: 1, lotName: 'A区停车场' },
    { id: 2, lotName: 'B区停车场' },
    { id: 3, lotName: 'C区停车场' }
])

const statistics = ref({
    totalCount: 1250,
    todayCount: 45,
    totalIncome: 12500,
    todayIncome: 850
})

const currentRecord = ref({})
const dateRange = ref([])

// 分页
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
})

// 搜索表单
const searchForm = reactive({
  lotId: null as number | null,
  licensePlate: '',
  paymentStatus: null as number | null,
  recordType: null as number | null,
  startTime: null as string | null,
  endTime: null as string | null
})

// 入场表单
const entryForm = reactive({
    lotId: null,
    licensePlate: ''
})

// 出场表单
const exitForm = reactive({
    licensePlate: ''
})

// 表单验证规则
const entryRules: FormRules = {
    lotId: [{ required: true, message: '请选择停车场', trigger: 'change' }],
    licensePlate: [{ required: true, message: '请输入车牌号', trigger: 'blur' }]
}

const exitRules: FormRules = {
    licensePlate: [{ required: true, message: '请输入车牌号', trigger: 'blur' }]
}

// 过滤后的表格数据
const filteredTableData = computed(() => {
    let filtered = [...allTableData.value]
    
    // 停车场过滤
    if (searchForm.lotId) {
        const lot = parkingLots.value.find(l => l.id === searchForm.lotId)
        if (lot) {
            filtered = filtered.filter(item => item.lotName === lot.lotName)
        }
    }
    
    // 车牌号过滤
    if (searchForm.licensePlate) {
        filtered = filtered.filter(item => 
            item.licensePlate.toLowerCase().includes(searchForm.licensePlate.toLowerCase())
        )
    }
    
    // 支付状态过滤
    if (searchForm.paymentStatus !== null) {
        filtered = filtered.filter(item => item.paymentStatus === searchForm.paymentStatus)
    }
    
    // 记录类型过滤
    if (searchForm.recordType !== null) {
        filtered = filtered.filter(item => item.recordType === searchForm.recordType)
    }
    
        // 时间范围过滤
    if (searchForm.startTime && searchForm.endTime) {
      filtered = filtered.filter(item => {
        const entryTime = new Date(item.entryTime)
        const startTime = new Date(searchForm.startTime!)
        const endTime = new Date(searchForm.endTime!)
        return entryTime >= startTime && entryTime <= endTime
      })
    }
    
    // 更新分页总数
    pagination.total = filtered.length
    
    // 分页
    const start = (pagination.current - 1) * pagination.size
    const end = start + pagination.size
    return filtered.slice(start, end)
})

// 监听日期范围变化
watch(dateRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    searchForm.startTime = newVal[0] || null
    searchForm.endTime = newVal[1] || null
  } else {
    searchForm.startTime = null
    searchForm.endTime = null
  }
})

// 搜索
const handleSearch = () => {
    pagination.current = 1
    showMessage({ type: 'success', message: '搜索完成' })
}

// 重置
const handleReset = () => {
    Object.assign(searchForm, {
        lotId: null,
        licensePlate: '',
        paymentStatus: null,
        recordType: null,
        startTime: null,
        endTime: null
    })
    dateRange.value = []
    pagination.current = 1
    showMessage({ type: 'success', message: '重置完成' })
}

// 刷新
const handleRefresh = () => {
    showMessage({ type: 'success', message: '数据已刷新' })
}

// 车辆入场
const handleVehicleEntry = () => {
    Object.assign(entryForm, {
        lotId: null,
        licensePlate: ''
    })
    entryDialogVisible.value = true
}

// 车辆出场
const handleVehicleExit = () => {
    Object.assign(exitForm, {
        licensePlate: ''
    })
    exitDialogVisible.value = true
}

// 详情
const handleDetail = (row: any) => {
    currentRecord.value = row
    detailDialogVisible.value = true
}

// 计算费用
const handleCalculateFee = (row: any) => {
    const fee = Math.floor(Math.random() * 30) + 10
    showMessage({ type: 'info', message: `停车费用: ¥${fee}` })
}

// 支付
const handlePayment = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定要支付该停车费用吗？', '提示', {
            type: 'warning'
        })
        showMessage({ type: 'success', message: '支付成功' })
        // 更新本地数据
        const index = allTableData.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
            allTableData.value[index].paymentStatus = 1
            allTableData.value[index].paymentStatusName = '已支付'
        }
    } catch (error) {
        if (error !== 'cancel') {
            showMessage({ type: 'error', message: '支付失败' })
        }
    }
}

// 导出
const handleExport = () => {
    showMessage({ type: 'success', message: '导出功能已执行，文件已下载到本地' })
}

// 入场提交
const handleEntrySubmit = async () => {
    if (!entryFormRef.value) return
    
    try {
        await entryFormRef.value.validate()
        submitLoading.value = true
        
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 添加新的停车记录
        const newRecord = {
            id: allTableData.value.length + 1,
            recordNo: `PR${new Date().getTime()}`,
            lotName: parkingLots.value.find(l => l.id === entryForm.lotId)?.lotName || '',
            spaceNo: `${String.fromCharCode(65 + Math.floor(Math.random() * 3))}-${String(Math.floor(Math.random() * 100)).padStart(3, '0')}`,
            licensePlate: entryForm.licensePlate,
            entryTime: new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            }).replace(/\//g, '-'),
            exitTime: null,
            parkingDuration: null,
            parkingFee: 0,
            paymentStatus: 0,
            paymentStatusName: '未支付',
            recordType: 1,
            recordTypeName: '临时停车'
        }
        
        allTableData.value.unshift(newRecord)
        showMessage({ type: 'success', message: '车辆入场成功' })
        
        entryDialogVisible.value = false
    } catch (error) {
        showMessage({ type: 'error', message: '车辆入场失败' })
    } finally {
        submitLoading.value = false
    }
}

// 出场提交
const handleExitSubmit = async () => {
    if (!exitFormRef.value) return
    
    try {
        await exitFormRef.value.validate()
        submitLoading.value = true
        
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 查找对应的停车记录
        const record = allTableData.value.find(item => 
            item.licensePlate === exitForm.licensePlate && !item.exitTime
        )
        
        if (!record) {
            showMessage({ type: 'error', message: '未找到该车辆的停车记录' })
            return
        }
        
        // 更新记录
        const exitTime = new Date()
        const entryTime = new Date(record.entryTime)
        const duration = Math.floor((exitTime.getTime() - entryTime.getTime()) / (1000 * 60))
        const fee = Math.floor(duration / 60) * 5 + (duration % 60 > 0 ? 5 : 0)
        
        record.exitTime = exitTime.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        }).replace(/\//g, '-')
        record.parkingDuration = duration
        record.parkingFee = fee
        
        showMessage({ type: 'success', message: '车辆出场成功' })
        exitDialogVisible.value = false
    } catch (error) {
        showMessage({ type: 'error', message: '车辆出场失败' })
    } finally {
        submitLoading.value = false
    }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
}

// 当前页改变
const handleCurrentChange = (current: number) => {
    pagination.current = current
}

// 初始化
onMounted(() => {
    pagination.total = allTableData.value.length
})
</script>

<style scoped>
.record-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.statistics-card {
    margin-bottom: 20px;
}

.statistics-item {
    text-align: center;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 8px;
}

.statistics-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 10px;
}

.statistics-value {
    font-size: 24px;
    font-weight: bold;
    color: #409eff;
}

.operation-card {
    margin-bottom: 20px;
}

.table-card {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}
</style>
